<?php

namespace app\common\command;

use app\common\model\FaceDevice;
use app\common\model\FaceDevicePush;
use app\common\model\Order;
use app\common\model\OrderDetail;
use app\common\service\FaceDeviceService;
use app\common\service\OrderService;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;

/**
 * 临时性的业务或测试处理
 */
class MysqlAsync extends Command
{
    public $output;

    private $dbOld;
    private $dbNew;

    protected function configure()
    {
        $this->setName('MysqlAsync')->setDescription('MYSQL增量同步');
    }

    /**
     * 执行
     * @param Input $input
     * @param Output $output
     * @return int|void|null
     */
    public function execute(Input $input, Output $output)
    {
        $output->writeln('MysqlAsync START ' . date('Y-m-d H:i:s'));

        $this->output = $output;
        $this->main();
        $output->writeln('MysqlAsync END ' . date('Y-m-d H:i:s'));
    }

    public function main()
    {
        $this->dbOld = $db1 = Db::connect('mysql');
        $this->dbNew = $db2 = Db::connect('mysql2');
        //找数据表列表
        $tables1 = $db1->query('SHOW TABLES');
        $dbOldTable = [];
        foreach ($tables1 as $index => $table) {
            //取表名：
            $tableName = $table['Tables_in_' . env('DB_NAME')];
            //$this->writeln("表格" . $index . "：" . print_r($tableName, true));
            $dbOldTable[] = $tableName;
        }
        $dbNewTable = [];
        $tables2 = $db2->query('SHOW TABLES');
        foreach ($tables2 as $index => $table) {
            //取表名：
            $tableName = $table['Tables_in_' . env('DB_NAME2')];
            // $this->writeln("表格" . $index . "：" . print_r($tableName, true));
            $dbNewTable [] = $tableName;
        }
        $this->compareTable($dbOldTable, $dbNewTable);
    }

    private function compareTable($dbOldTable, $dbNewTable)
    {
        foreach ($dbOldTable as $table) {
            foreach ($dbNewTable as $table2) {
                if ($table == $table2) {
                    $this->asyncTable($table);
                }
            }
        }
    }

    private function asyncTable($table)
    {
        $this->output->writeln(".");
        $this->writeln("表格" . $table . "：开始同步");
        $pkName = "";//主键
        //找表格主键
        $pk = $this->dbOld->query('SHOW INDEX FROM ' . $table . ' WHERE Key_name = \'PRIMARY\'');
        if (count($pk) > 0) {
            $pkName = $pk[0]['Column_name'];
            $this->writeln("表格" . $table . "：主键" . $pkName);
        }
        if (!$pkName) {
            $this->writeln("表格" . $table . "：没有主键，跳过");
            return;
        }
        $orderKey =  $pkName ;
        $oldMaxRecord = $this->dbOld->table($table)->order("$orderKey desc")->find();
        $newMaxRecord = $this->dbNew->table($table)->order("$orderKey desc")->find();
        if (!$newMaxRecord) {
            $this->writeln("表格" . $table . "：新表没有数据，跳过");
            return;
        }
        if ($oldMaxRecord && $oldMaxRecord[$pkName] >= $newMaxRecord[$pkName]) {
            $this->writeln("两张表主键一致，不需要增量同步");
            return;
        }
        $this->writeln("表格" . $table . "：开始增量同步");
        //找列表记录
        $where = [];
        if ($oldMaxRecord) {
            $where[] = [$pkName, ">", $oldMaxRecord[$pkName]];
        }
        $dbOld = $this->dbOld;
        $this->dbNew->table($table)->where($where)->order("$orderKey asc")->chunk(1000, function ($list) use ($table, $pkName, $dbOld) {
            //批量插入数据库
            $count = count($list);
            $res = $dbOld->table($table)->insertAll($list->toArray());
            $this->writeln("同步 " . $count . " 条数据，结果：" . $res);
        });
        $this->writeln("表格" . $table . "：结束增量同步");

    }


    private function writeln($obj)
    {
        $str = "[" . getNow() . ":]" . print_r($obj, true);
        $this->output->writeln("" . $str);
    }
}
